package xyz.xtt.asset.mq;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import com.google.common.primitives.Longs;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import xyz.xtt.asset.entity.TblAssetTransaction;
import xyz.xtt.asset.service.IRoseService;
import xyz.xtt.asset.service.ITblAssetTransactionService;
import xyz.xtt.pay.client.response.TblPayOrderDto;

/**
 * 审核付款后铸造
 *
 * @author dale
 * @since 2024/12/30
 **/
@RefreshScope
@Slf4j
@Component
@RocketMQMessageListener(topic = "${rocketmq.pay.order.status.change.topic:nft_pay_order_status_change}", selectorExpression = "ROSE_MINT:PAY_SUCCESS", consumerGroup = "${rocketmq.consumer.group.rose}")
public class PayRoseConsumer implements RocketMQListener<MessageExt> {
	@Autowired
	private IRoseService iRoseService;
	@Autowired
	private ITblAssetTransactionService iTblAssetTransactionService;

	@Override
	public void onMessage(MessageExt msg) {
		String msgId = msg.getMsgId();
		int reconsumeTimes = msg.getReconsumeTimes();
		String message = new String(msg.getBody(), StandardCharsets.UTF_8);
		log.info("PayRoseConsumer msgId:{},reconsumeTimes:{},message: {}", msgId, reconsumeTimes, message);
		if (StringUtils.isEmpty(message)) {
			return;
		}
		if (!JSONUtil.isTypeJSON(message)) {
			log.warn("PayRoseConsumer Received message: {} is not json", message);
			return;
		}
		try {
			TblPayOrderDto payOrderDto = JSONUtil.toBean(message, TblPayOrderDto.class);
			if (Objects.isNull(payOrderDto)) {
				log.warn("PayRoseConsumer JSONUtil.toBean is null. message:{}", message);
				return;
			}
			// 已经处理过交易了
			String businessRefId = payOrderDto.getBusinessRefId();
			Long orderId = Longs.tryParse(businessRefId);
			if (Objects.nonNull(orderId) && orderId.longValue() > 0) {
				TblAssetTransaction transaction = iTblAssetTransactionService.getById(orderId);
				if (Objects.nonNull(transaction)) {
					log.warn("PayRoseConsumer transaction not null message:{}, businessRefId:{}", message, businessRefId);
					return;
				}
			}
			iRoseService.rosePayAfter(payOrderDto, false);
		} catch (Exception e) {
			log.info("PayRoseConsumer consume failed. message:{} ex:{}", message, e.getMessage(), e);
			throw new RuntimeException("PayRoseConsumer Consumer Message exception", e);
		}
	}

}
